<?php

namespace app\admin\controller;

use org\Crypt3despk7;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;

/**
 * 后台登录
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{
    /**
     * 后台登录
     * @return mixed
     */
    public function index()
    {
        //输出当前上传类型
        $oss_config = get_oss_upload_params();
        $this->assign('upload_type', $oss_config['upload_type']);

        if (Session::has('admin_id') && Session::has('admin_token')) {
            $this->redirect('admin/index/index');
        } else {
            return $this->fetch();
        }
    }

    public function login()
    {
        $request = Request::instance();
        $param = $request->param();

        if ($this->request->isPost()) {
            $data = $this->request->only(['username', 'password', 'verify']);
            $validate_result = $this->validate($data, 'Login');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data = [];
                $data['username'] = $param['username'];
                $data['password'] = md5($param['password'] . config('salt'));
                $data['app_id'] = config('admin_app.app_id');
                $time = time();
                $data['time'] = $time;
                $data['app_secret_des'] = md5(config('admin_app.app_id') . config('admin_app.app_secret') . $time);

                try {
                    $result = doCurl(config('admin_app.url')['admin_login'], 1, $data);
                    $res = json_decode($result, true);
                    if($res['code'] != 200) {
                        return json($res);
                    }
                    Session::set('admin_id', $res['admin_id']);
                    Session::set('admin_name', $res['admin_name']);
                    Session::set('admin_token', $res['admin_token']);
                    Session::set('admin_time_out', $res['admin_time_out']);
                    return json($res);
                } catch (Exception $e) {
                    $data['code'] = 401;
                    $data['msg'] = '未知错误';
                    $data['error_code'] = 10001;
                    return json($data);
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::delete('admin_id');
        Session::delete('admin_name');
        Session::delete('admin_token');
        Session::delete('admin_time_out');
        $this->success('退出成功', 'admin/login/index');
    }
}
